//package com.dongzili.postgresql.common.mybatisplus;
//
//import org.apache.ibatis.executor.statement.StatementHandler;
//import org.apache.ibatis.mapping.BoundSql;
//import org.apache.ibatis.mapping.MappedStatement;
//import org.apache.ibatis.mapping.SqlCommandType;
//import org.apache.ibatis.plugin.*;
//import org.apache.ibatis.reflection.MetaObject;
//import org.apache.ibatis.reflection.SystemMetaObject;
//import java.lang.reflect.Field;
//import java.sql.Connection;
//import java.util.Properties;
//
//@Intercepts({@Signature(
//    type = StatementHandler.class,
//    method = "prepare",
//    args = {Connection.class, Integer.class}
//)})
//public class PostgreSqlTableNameInterceptor implements Interceptor {
//
//    @Override
//    public Object intercept(Invocation invocation) throws Throwable {
//        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
//        MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
//        MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
//        SqlCommandType commandType = mappedStatement.getSqlCommandType();
//
//        // 替代 SqlCommandType.isDml()，兼容低版本
//        boolean isDmlOrSelect = commandType == SqlCommandType.SELECT
//                || commandType == SqlCommandType.INSERT
//                || commandType == SqlCommandType.UPDATE
//                || commandType == SqlCommandType.DELETE;
//
//        if (isDmlOrSelect) {
//            BoundSql boundSql = statementHandler.getBoundSql();
//            String sql = boundSql.getSql();
//            String tableName = extractTableName(sql);
//
//            if (tableName != null && !tableName.startsWith("\"")) {
//                sql = sql.replace(tableName, "\"" + tableName + "\"");
//                // 通过反射修改 BoundSql 的 sql 字段（兼容所有版本）
//                Field sqlField = BoundSql.class.getDeclaredField("sql");
//                sqlField.setAccessible(true);
//                sqlField.set(boundSql, sql);
//            }
//        }
//
//        return invocation.proceed();
//    }
//
//    // 提取表名（简化版，支持单表）
//    private String extractTableName(String sql) {
//        String lowerSql = sql.toLowerCase().trim();
//        int fromIndex = lowerSql.indexOf("from ");
//        if (fromIndex == -1) fromIndex = lowerSql.indexOf("into ");
//        if (fromIndex == -1) fromIndex = lowerSql.indexOf("update ");
//        if (fromIndex == -1) return null;
//
//        String tablePart = sql.substring(fromIndex + 5).trim();
//        int spaceIndex = tablePart.indexOf(" ");
//        return spaceIndex == -1 ? tablePart : tablePart.substring(0, spaceIndex);
//    }
//
//    @Override
//    public Object plugin(Object target) {
//        return Plugin.wrap(target, this);
//    }
//
//    @Override
//    public void setProperties(Properties properties) {}
//}